package com.bw.apps.local

import android.util.Log
import android.view.LayoutInflater
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.viewbinding.ViewBinding
import com.alibaba.android.arouter.facade.annotation.Route
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.bw.apps.databinding.ActivityLocalAppsBinding
import com.bw.apps.local.entity.LocalAppsEntity
import com.bw.common.mvi.BaseActivity
import com.bw.widget.decoration.SignLineDecoration
import io.virtualapp.hook_sdk.app.InstallAppUtils
import kotlinx.coroutines.launch


@Route(path = "/apps/LocalAppsActivity")
class LocalAppsActivity : BaseActivity<ActivityLocalAppsBinding,LocalAppsViewModel>(){

    private val localAdapter : LocalAppsAdapter by lazy { LocalAppsAdapter() }
    private val installAppUtils : InstallAppUtils by lazy { InstallAppUtils() }
    private var flag = false
    var mLocationClient: LocationClient? = null
    private val myListener = MyLocationListener()
    override fun createVM(): LocalAppsViewModel {
        return viewModels<LocalAppsViewModel>().value
    }

    override fun initView() {
        v.localAppsBar.backImg.setOnClickListener { finish() }
        v.localAppsBar.titleTv.text = "已安装应用"
        v.localAppsBar.moreTv.text = "编辑"
        v.localAppsBar.moreTv.setOnClickListener {
            val datas = ArrayList<LocalAppsEntity>()
            if (v.localAppsBar.moreTv.text.equals("编辑")){
                v.localAppsBar.moreTv.text="保存"
                localAdapter.data.forEach {
                    datas.add( LocalAppsEntity(
                        it.packageName, it.apkPath, it.libPath,
                        it.dependSystem, it.appId,it.edtFlag,true) )
                }
            }else{
                v.localAppsBar.moreTv.text="编辑"
                localAdapter.data.forEach {
                    datas.add( LocalAppsEntity(
                        it.packageName, it.apkPath, it.libPath,
                        it.dependSystem, it.appId,it.edtFlag,false) )
                }
            }
            localAdapter.setNewInstance(datas)
        }
        val manager = GridLayoutManager(this,3)
        manager.orientation = GridLayoutManager.VERTICAL
        v.localAppsRv.layoutManager = manager
        v.localAppsRv.addItemDecoration(SignLineDecoration(this))
        localAdapter.setOnItemCLickListener { adapter, position ->
//            if (!flag){
//                Log.e("ZXY","不在使用范围内")
//                ToastUtils.showShort("不在使用范围内")
//                return@setOnItemCLickListener
//            }

            installAppUtils.launchApp( localAdapter.data.get(position).packageName)
        }
        localAdapter.setOnItemChildCLickListener{ adapter,id, position->
            val entity = LocalAppsEntity( localAdapter.data[position].packageName,
                localAdapter.data[position].apkPath, localAdapter.data[position].libPath,
                localAdapter.data[position].dependSystem, localAdapter.data[position].appId,
                !localAdapter.data[position].edtFlag, localAdapter.data[position].showEdt)
            localAdapter.data[position] = entity
            localAdapter.notifyItemRangeChanged(position,1)

        }
        v.localAppsRv.adapter = localAdapter
        initLocation()
    }

    override fun initData() {
        vm.selLocalApps()
    }

    override fun bindState() {
        lifecycleScope.launch{
            vm.mutableContainer.uiStateFlow.collect{
                LogUtils.e("本地应用数量${it.datas.size}")
                if (it.localAppState){
                    localAdapter.setNewInstance(it.datas)
                }
            }
        }
    }

    override fun createViewBinding(): ViewBinding {
        return ActivityLocalAppsBinding.inflate(LayoutInflater.from(this))
    }

    private fun initLocation(){
        LocationClient.setAgreePrivacy(true)
        mLocationClient =  LocationClient(getApplicationContext())
        //声明LocationClient类
        mLocationClient!!.registerLocationListener(myListener)
        val option : LocationClientOption =  LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Battery_Saving);
        //可选，设置定位模式，默认高精度
        //LocationMode.Hight_Accuracy：高精度；
        //LocationMode. Battery_Saving：低功耗；
        //LocationMode. Device_Sensors：仅使用设备；
        //LocationMode.Fuzzy_Locating, 模糊定位模式；v9.2.8版本开始支持，可以降低API的调用频率，但同时也会降低定位精度；
        option.setCoorType("bd09ll");
        //可选，设置返回经纬度坐标类型，默认GCJ02
        //GCJ02：国测局坐标；
        //BD09ll：百度经纬度坐标；
        //BD09：百度墨卡托坐标；
        //海外地区定位，无需设置坐标类型，统一返回WGS84类型坐标
        option.setScanSpan(1000)
//可选，设置发起定位请求的间隔，int类型，单位ms
//如果设置为0，则代表单次定位，即仅定位一次，默认为0
//如果设置非0，需设置1000ms以上才有效
        option.setOpenGnss(true);
//可选，设置是否使用卫星定位，默认false
//使用高精度和仅用设备两种定位模式的，参数必须设置为true
        option.setIgnoreKillProcess(false);
//可选，定位SDK内部是一个service，并放到了独立进程。
//设置是否在stop的时候杀死这个进程，默认（建议）不杀死，即setIgnoreKillProcess(true)
        option.SetIgnoreCacheException(false);
//可选，设置是否收集Crash信息，默认收集，即参数为false
        option.setWifiCacheTimeOut(5*60*1000);
//可选，V7.2版本新增能力
//如果设置了该接口，首次启动定位时，会先判断当前Wi-Fi是否超出有效期，若超出有效期，会先重新扫描Wi-Fi，然后定位
        option.setEnableSimulateGnss(false);
//可选，设置是否需要过滤卫星定位仿真结果，默认需要，即参数为false
        option.setNeedNewVersionRgc(true);
//可选，设置是否需要最新版本的地址信息。默认需要，即参数为true
        mLocationClient!!.setLocOption(option);
//mLocationClient为第二步初始化过的LocationClient对象
//需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
//更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明
        mLocationClient!!.start()
    }

    override fun onStop() {
        super.onStop()
        mLocationClient!!.stop()
    }

    inner class MyLocationListener: BDAbstractLocationListener() {
        override fun onReceiveLocation(location : BDLocation){
            val latitude: Double = location.getLatitude() //获取纬度信息
            val longitude: Double = location.getLongitude() //获取经度信息
            Log.e("ZXY", "latitude:$latitude&&longitude:$longitude")
            if(latitude>121&&longitude<60){
                flag = true
            }

        }
    }

}